﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using XPTable.Models;
using XPTable.Editors;
using System.Net.Mail;
using System.IO;
using System.Xml.Serialization;

namespace PolarSonicLink
{
    public partial class SessionViewer : Form
    {
        enum ColumnNames
        {
            DateTime = 0,
            RideTime,
            Distance,
            MaxSpeed,
            HRAverage,
            HRMax,
            Route,
            Bike,
            RideType,
            Comment
        }

        public SessionViewer(SessionDecoder decodedSession, CyclogsUserValues cyclogsUserValues)
        {
            InitializeComponent();
            m_decodedSession = decodedSession;
            m_cyclogsUserValues = cyclogsUserValues;
        }

        private SessionDecoder m_decodedSession;
        private CyclogsUserValues m_cyclogsUserValues;

        private void SessionViewer_Load(object sender, EventArgs e)
        {
            labelDateOfBirth.Text = m_decodedSession.DateOfBirth.ToLongDateString();
            labelRiderWeight.Text = m_decodedSession.RiderWeight.ToString() + "kg";
            labelRiderHeight.Text = m_decodedSession.RiderHeight.ToString() + "cm";
            labelHRMax.Text = m_decodedSession.HRMaxUser.ToString() + " bpm";
            labelHRSit.Text = m_decodedSession.HRSitUser.ToString() + " bpm";

            foreach ( RideInformation thisRide in m_decodedSession.RideInformation )
            {
                AddRideDetails(thisRide);
            }
        }

        private void AddRideDetails(RideInformation thisRide)
        {
            listViewRideInformation.SuspendLayout();
            
            ListViewItem thisRideListView = new ListViewItem(thisRide.ToListViewStrings());
            listViewRideInformation.Items.Add(thisRideListView);

            foreach(ColumnHeader columnHeader in listViewRideInformation.Columns)
            {
                columnHeader.Width = -2;
            }

            listViewRideInformation.ResumeLayout();
        }

        private void tabControlSession_Selected(object sender, TabControlEventArgs e)
        {
            tableCyclogs.SuspendLayout();

            tableModelCyclogs.Rows.Clear();

            int rowNumber = 0;
            foreach ( RideInformation thisInfo in m_decodedSession.RideInformation )
            {
                tableModelCyclogs.Rows.Add(new Row());
                tableModelCyclogs.Rows[rowNumber].Cells.Add(new Cell(thisInfo.StartDateTime.ToShortDateString()));
                tableModelCyclogs.Rows[rowNumber].Cells.Add(new Cell(thisInfo.ExerciseTime.ToString()));
                tableModelCyclogs.Rows[rowNumber].Cells.Add(new Cell(thisInfo.Distance.ToString()));
                tableModelCyclogs.Rows[rowNumber].Cells.Add(new Cell(thisInfo.MaximumSpeed.ToString()));
                tableModelCyclogs.Rows[rowNumber].Cells.Add(new Cell(thisInfo.HRAverage.ToString()));
                tableModelCyclogs.Rows[rowNumber].Cells.Add(new Cell(thisInfo.HRMaximum.ToString()));

                tableModelCyclogs.Rows[rowNumber].Cells.Add(new Cell("Trowbidge work"));
                tableModelCyclogs.Rows[rowNumber].Cells.Add(new Cell("Monoc"));
                tableModelCyclogs.Rows[rowNumber].Cells.Add(new Cell("Commute"));
                tableModelCyclogs.Rows[rowNumber].Cells.Add(new Cell(""));

                rowNumber++;
            }

            tableCyclogs.ResumeLayout();
        }

        private void tableCyclogs_BeginEditing(object sender, XPTable.Events.CellEditEventArgs e)
        {
            if ( e.Editor is ComboBoxCellEditor )
            {
                ComboBoxCellEditor thisEditor = (ComboBoxCellEditor) e.Editor;

                thisEditor.DropDownStyle = DropDownStyle.DropDownList;
                thisEditor.MaxDropDownItems = 20;

                if ( e.Column == (int) ColumnNames.Route )
                {
                    ( (ComboBoxCellEditor) e.Editor ).Items.Clear();
                    ( (ComboBoxCellEditor) e.Editor ).Items.AddRange(m_cyclogsUserValues.Routes.ToArray());
                }
                else if ( e.Column == (int) ColumnNames.Bike )
                {
                    ( (ComboBoxCellEditor) e.Editor ).Items.Clear();
                    ( (ComboBoxCellEditor) e.Editor ).Items.AddRange(m_cyclogsUserValues.Bikes.ToArray());
                }
                else if ( e.Column == (int) ColumnNames.RideType )
                {
                    ( (ComboBoxCellEditor) e.Editor ).Items.Clear();
                    ( (ComboBoxCellEditor) e.Editor ).Items.AddRange(m_cyclogsUserValues.RideTypes.ToArray());
                }
            }
        }

        private void tableCyclogs_CellDoubleClick(object sender, XPTable.Events.CellMouseEventArgs e)
        {
            if ( e.Column == (int) ColumnNames.Comment )
            {
                StringEntry thisStringEntry = new StringEntry("Enter Comment");

                if ( thisStringEntry.ShowDialog() == DialogResult.OK )
                {
                    e.Cell.Text = thisStringEntry.enteredString;
                }
            }
        }

        private void buttonSaveXML_Click(object sender, EventArgs e)
        {
            SaveFileDialog fileSaveDialog = new SaveFileDialog();

            fileSaveDialog.CheckPathExists = true;
            fileSaveDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            fileSaveDialog.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*";

            if ( fileSaveDialog.ShowDialog() == DialogResult.OK )
            {
                XmlSerializer s = new XmlSerializer(typeof(SessionDecoder));
                TextWriter w = new StreamWriter(fileSaveDialog.FileName);
                s.Serialize(w, m_decodedSession);
                w.Close();
            }
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            //MailMessage mailMessage = new MailMessage();
            string username = "UserName," + m_cyclogsUserValues.UserName + ",,,,,,,,,,,,,";
            string titles = "RideDate,RouteName,Distance,Hours,Minutes,Seconds,MaxSpeed,BikeName,RideType,MaxHR,AvgHR,Comments,Weight,TeamName,Rating";
            List<string> body = new List<string>();
            //string dummy = "11/05/2009,test,0,0,0,,0,test,test,0,0,test,0,test,0";

            foreach ( Row thisRow in tableModelCyclogs.Rows )
            {
                TimeSpan timeSpan = TimeSpan.Parse(thisRow.Cells[(int) ColumnNames.RideTime].Text);

                string thisEntry =
                    thisRow.Cells[(int) ColumnNames.DateTime].Text + "," + 
                    thisRow.Cells[(int) ColumnNames.Route].Text + "," + 
                    thisRow.Cells[(int) ColumnNames.Distance].Text + "," +
                    timeSpan.Hours.ToString() + "," +
                    timeSpan.Minutes.ToString() + "," +
                    timeSpan.Seconds.ToString() + "," +
                    thisRow.Cells[(int) ColumnNames.MaxSpeed].Text + "," +
                    thisRow.Cells[(int) ColumnNames.Bike].Text + "," +
                    thisRow.Cells[(int) ColumnNames.RideType].Text + "," +
                    thisRow.Cells[(int) ColumnNames.HRMax].Text + "," +
                    thisRow.Cells[(int) ColumnNames.HRAverage].Text + "," +
                    thisRow.Cells[(int) ColumnNames.Comment].Text + "," +
                    "0,,0";

                body.Add(thisEntry);
            }

            string myDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            WriteCSVFile(myDocuments + Path.DirectorySeparatorChar + "ToSendToCyclogs.csv", titles, username, body);
        }

        public class CSVLine
        {
            public static bool Contains(List<CSVLine> theList, string toFind)
            {
                bool found = false;

                foreach ( CSVLine theLine in theList )
                {
                    if ( theLine.IsSameLine(toFind) )
                    {
                        found = true;
                        break;
                    }
                }

                return ( found );
            }

            public CSVLine(string theLine)
            {
                string[] split = theLine.Split(',');

                if ( split.Length >= 6 )
                {
                    RideDate = split[0];
                    RouteName = split[1];
                    Distance = split[2];
                    Hours = split[3];
                    Minutes = split[4];
                    Seconds = split[5];
                    MaxSpeed = split[6];
                }
            }

            public bool IsSameLine(string theLine) 
            {
                string[] split = theLine.Split(',');
                bool isSame = false;

                if ( split.Length >= 6 )
                {
                    //RideDate,RouteName,Distance,Hours,Minutes,Seconds,MaxSpeed
                    if ( ( RideDate == split[0] ) && ( Distance == split[2] ) &&
                        ( Hours == split[3] ) && ( Minutes == split[4] ) &&
                        ( Seconds == split[5] ) && ( MaxSpeed == split[6] ) )
                    {
                        isSame = true;
                    }
                }

                return (isSame);
            }

            public override string ToString()
            {
                string thisItem;

                thisItem = RideDate + " " + RouteName + " " + Distance + " " + Hours + ":" + Minutes + ":" + Seconds;

                return ( thisItem );
            }

            string RideDate { get; set; }
            string RouteName { get; set; }
            string Distance { get; set; }
            string Hours { get; set; }
            string Minutes { get; set; }
            string Seconds { get; set; }
            string MaxSpeed { get; set; }
        }

        private void WriteCSVFile(string fileName, string titles, string username, List<string> body)
        {
            try
            {
                bool fileExists = File.Exists(fileName);
                List<CSVLine> currentCSVLines = new List<CSVLine>();

                if ( fileExists )
                {
                    File.Copy(fileName, fileName + ".old", true);

                    StreamReader reader = new StreamReader(fileName);

                    while ( !reader.EndOfStream )
                    {
                        //RideDate,RouteName,Distance,Hours,Minutes,Seconds,MaxSpeed
                        currentCSVLines.Add(new CSVLine(reader.ReadLine()));
                    }

                    reader.Close();
                }

                StreamWriter writer = new StreamWriter(fileName, true);

                if ( !fileExists )
                {
                    writer.WriteLine(username);
                    writer.WriteLine(titles);
                }

                foreach ( string thisEntry in body )
                {
                    if ( !CSVLine.Contains(currentCSVLines, thisEntry) )
                    {
                        writer.WriteLine(thisEntry);
                    }
                    else
                    {
                        MessageBox.Show("Item already found in CSV file\r\n" + new CSVLine(thisEntry).ToString(), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }

                writer.Write("\r\n");
                writer.Close();

                MessageBox.Show("File successfully saved/updated in location;\r\n\r\n" + fileName, "File saved...", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch ( Exception ex )
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
